package com.wifi;

import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.Vibrator;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.squareup.okhttp.OkHttpClient;
import com.wifi.IBackService.IBackService;
import com.wifi.IBackService.ThreadService;
import com.wifi.eshipewifi.InitActivity;
import com.wifi.eshipewifi.R;
import com.wifi.eshipewifi.SocThread;
import com.wifi.imp.MessageListener;
import com.wifi.imp.ViewListener;
import com.wifi.service.LocationService;
import com.wifi.utils.Utils;
import com.wifi.utils.WifiUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/8/11.
 */
public class BaseApplication extends Application {

    public String ip=null;
    public String currentSsid=null;
    public String ssid;
    public String password;
    public boolean toastState;
    public String lastUpdate;//上一次更新的固件名
    SharedPreferences sp;

    private Intent mServiceIntent;
    private MessageBackReciver mReciver;
    private IntentFilter mIntentFilter;
    private LocalBroadcastManager mLocalBroadcastManager;
    private WifiManager wm;
    //百度
    public LocationService locationService;
    public Vibrator mVibrator;
    @Override
    public void onCreate() {
        super.onCreate();

        sp= getSharedPreferences("wifiSetting", Activity.MODE_PRIVATE);
        ssid = sp.getString("ssid", "sn1111111");//todo 以后要改,默认账号 sn1111111要改
        password = sp.getString("password", "czd5d323");


        wm = (WifiManager) getSystemService(WIFI_SERVICE);
        DhcpInfo di = wm.getDhcpInfo();
        long getewayIpL = di.gateway;
        String getwayIpS = Utils.long2ip(getewayIpL);//网关地址
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("ip",getwayIpS);
        edit.commit();


        OkHttpClient client =
                OkHttpUtils.getInstance().getOkHttpClient();
        client.setConnectTimeout(100000, TimeUnit.MILLISECONDS);

        //开启广播
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mReciver = new MessageBackReciver();
        mServiceIntent = new Intent(this, ThreadService.class);
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ThreadService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(ThreadService.MESSAGE_ACTION);
        mIntentFilter.addAction(ThreadService.WIFI_REBOOT);
        mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
        bindService(mServiceIntent, conn, BIND_AUTO_CREATE);

        /***
         * 初始化定位sdk，建议在Application中创建
         */
        locationService = new LocationService(getApplicationContext());
        mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        SDKInitializer.initialize(getApplicationContext());

    }

    private IBackService iBackService;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            iBackService = null;
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iBackService = IBackService.Stub.asInterface(service);
        }
    };
    class MessageBackReciver extends BroadcastReceiver {
        private WeakReference<TextView> textView;
        public MessageBackReciver() {
        }
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ThreadService.HEART_BEAT_ACTION)) {

            }else if (action.equals(ThreadService.WIFI_REBOOT)) {//wifi重启
                String ssid = getSsid();
                String password = getPassword();
                WifiUtils wifiUtils=new WifiUtils(wm);
                wifiUtils.WifiRebootForSetName(ssid,password);
            }else {
                String message = intent.getStringExtra("message");
                if(message.indexOf("heartbeat")!=-1){
                    if(viewListener!=null){
                        viewListener.ViewSetListener();
                    }
                }else {
                    if(listener!=null)
                        listener.MessageGetListener(message);
                }
            }
        };
    }

    public void setNewSocket(){
        if(iBackService==null){
            mReciver = new MessageBackReciver();
            mServiceIntent = new Intent(this, ThreadService.class);
            mIntentFilter = new IntentFilter();
            mIntentFilter.addAction(ThreadService.HEART_BEAT_ACTION);
            mIntentFilter.addAction(ThreadService.MESSAGE_ACTION);
            mIntentFilter.addAction(ThreadService.WIFI_REBOOT);
            mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
            bindService(mServiceIntent, conn, BIND_AUTO_CREATE);
        }
        try {
            iBackService.getNetSocket();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    //发送Msg
    public boolean sendMsg(String msg){
        boolean isSend = false;//Send Content by socket
        try {
            if(iBackService==null){
                mReciver = new MessageBackReciver();
                mServiceIntent = new Intent(this, ThreadService.class);
                mIntentFilter = new IntentFilter();
                mIntentFilter.addAction(ThreadService.HEART_BEAT_ACTION);
                mIntentFilter.addAction(ThreadService.MESSAGE_ACTION);
                mIntentFilter.addAction(ThreadService.WIFI_REBOOT);
                mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
                bindService(mServiceIntent, conn, BIND_AUTO_CREATE);
            }
            isSend = iBackService.sendMessage(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return isSend;
    }


    //控制吐司弹出，数据一般状态下不弹出
    public void makeToast(Context context,String msg,boolean commom){
        toastState = sp.getBoolean("toastState", false);
        if(toastState || commom){//打开
            Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
        }
    }


    public boolean sendFile(String path){
        boolean isSend = false;
        try {
            if(iBackService==null){
                mReciver = new MessageBackReciver();
                mServiceIntent = new Intent(this, ThreadService.class);
                mIntentFilter = new IntentFilter();
                mIntentFilter.addAction(ThreadService.HEART_BEAT_ACTION);
                mIntentFilter.addAction(ThreadService.MESSAGE_ACTION);
                mIntentFilter.addAction(ThreadService.WIFI_REBOOT);
                mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
                bindService(mServiceIntent, conn, BIND_AUTO_CREATE);
            }
            isSend = iBackService.sendFile(path);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return isSend;
    }





    //设置消息监听
    MessageListener listener;
    ViewListener viewListener;
    public void setMsgListener(MessageListener listener){
        this.listener=listener;
    }

    public void setViewListener(ViewListener listener){
        this.viewListener=listener;
    }

    public String getLastUpdate(){
        lastUpdate = sp.getString("lastUpdate", "update.bin");
        return lastUpdate;
    }

    public void setLastUpdate(String lastUpdate){
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("lastUpdate",lastUpdate);
        edit.commit();
    }

    public String getSsid(){
        ssid = sp.getString("ssid", "sn1111111");//todo 以后要改,默认账号 sn1111111要改
        return ssid;
    }

    public void setSsid(String ssid){
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("ssid",ssid);
        edit.commit();
    }

    public void setPassword(String password){
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("password",password);
        edit.commit();
    }

    public String getPassword(){
        if(password==null)
            password = sp.getString("password", "czd5d323");
        return password;
    }

    public String getIp(){
        if(ip==null)
            ip = sp.getString("ip", "192.168.8.1");
        return ip;
    }

    public void setIp(String ip){
        this.ip=ip;
    }


    private SocThread thread=null;
    public void setThread(SocThread thread){
        this.thread=thread;
    }
    public SocThread getThread(Handler handlerin, Handler handlerout, Context context){
        if(thread==null){
            thread=new SocThread(handlerin,handlerout,context);
        }
        thread.setHandler(handlerin,handlerout);//重置handler
        return thread;
    }

}
